package com.sduonline.isdapp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sduonline.isdapp.model.WebAdmin;

public class WebAdminDao {

	private static ConnectionPool pool;

	public WebAdminDao() {
		if (pool == null) {
			pool = ConnectionPool.getInstance();
		}
	}

	public boolean save(WebAdmin admin) {
		Connection conn = pool.getConnection();
		String sql = "insert into isd_webadmin(username,password,web_id) values(?,?,?)";
		PreparedStatement ptmt = null;

		try {
			conn.setAutoCommit(false);

			ptmt = conn.prepareStatement(sql);

			ptmt.setString(1, admin.getUsername());
			ptmt.setString(2, admin.getPassword());
			ptmt.setInt(3, admin.getWeb_id());

			ptmt.execute();
			conn.commit();
			ptmt.close();
			conn.close();

			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return false;
			}
			return false;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public WebAdmin getByWebId(int web_id) {
		Connection conn = pool.getConnection();
		String sql = "select * from isd_webadmin where web_id = ? ";
		PreparedStatement ptmt = null;

		try {
			ptmt = conn.prepareStatement(sql);
			ptmt.setInt(1, web_id);
			ResultSet rs = ptmt.executeQuery();

			WebAdmin admin = new WebAdmin();
			if (rs.next()) {
				admin.setId(rs.getInt("id"));
				admin.setUsername(rs.getString("username"));
				admin.setPassword(rs.getString("password"));
				admin.setWeb_id(rs.getInt("web_id"));
			} else {
				admin = null;
			}
			ptmt.close();
			rs.close();
			conn.close();
			return admin;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
